package com.cuitrip.business.user;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.cuitrip.apiservice.ServiceBusiness;
import com.cuitrip.apiservice.UserBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.home.IndexActivity;
import com.cuitrip.business.home.trip.TripServiceListFragment;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.setting.SubmitSuccessActivity;
import com.cuitrip.business.setting.model.SubmitSuccessModel;
import com.cuitrip.business.tripservice.model.FormType;
import com.cuitrip.business.tripservice.model.ServiceInfo;
import com.cuitrip.business.tripservice.proxy.ServiceFormProxy;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.service.R;
import com.cuitrip.util.CountDownTimerUtil;
import com.cuitrip.util.JumpSuccessUtil;
import com.cuitrip.util.ResourceUtil;
import com.cuitrip.util.track.TrackUtil;
import com.jakewharton.rxbinding.view.RxView;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragment;
import com.lab.jumper.FragmentJumper;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.utils.MessageUtils;
import com.lab.utils.RxUtils;
import com.lab.utils.Utils;

import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * Created by sheena on 16/5/12.
 */
public class VerifyUserMoblieFragment extends CustomUiFragment implements IProxyCallback {

    @Bind(R.id.v1)
    View mStep1;

    @Bind(R.id.v2)
    View mStep2;

    @Bind(R.id.v3)
    View mStep3;

    @Bind(R.id.tv_code_select)
    TextView mCountryCode;

    @Bind(R.id.et_photo_number)
    EditText mPhotoNumber;

    @Bind(R.id.et_verified_code)
    EditText mVerifiedCode;

    @Bind(R.id.tv_send)
    TextView mSendBtn;


    private static final int REQUEST_CODE_COUNTRY_COED = 1;
    private static final int REQUEST_CODE_VERIFIED_SUC = 2;
    private static final int REQUEST_CODE_ID_SUCCESS = 0X01;


    private ApiProxy mApiProxy = new ApiProxy(this);
    private String countryCode = "86";
    private ServiceInfo mServiceInfo;
    private CtUserInfo mUserInfo;
    private CountDownTimer countDownTimer;

    public static VerifyUserMoblieFragment newInstance(ServiceInfo serviceInfo, CtUserInfo mUserInfo) {
        VerifyUserMoblieFragment verifyUserMoblieFragment = new VerifyUserMoblieFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(ServiceInfo.KEY, serviceInfo);
        bundle.putSerializable(CtUserInfo.KEY, mUserInfo);
        verifyUserMoblieFragment.setArguments(bundle);
        return verifyUserMoblieFragment;
    }


    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mTopbarMiddleAreaName = getString(R.string.trip_operation_profile_title_2);
        config.mRightStyle = CustomUiConfig.AreaStyle.TEXT_STYLE;
        config.mTopbarRightAreaName = getString(R.string.operation_skip);
        return config;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState, R.layout.fragment_verify_moblie);
        if (getArguments() != null) {
            mServiceInfo = (ServiceInfo) getArguments().getSerializable(ServiceInfo.KEY);
            mUserInfo = (CtUserInfo) getArguments().getSerializable(CtUserInfo.KEY);
        }
        return view;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this, getView());

    }

    private void initProgress() {
        mStep1.setBackgroundColor(ResourceUtil.getThemeColor());
        mStep2.setBackgroundColor(ResourceUtil.getThemeColor());
        if (CtUserInfo.ID_CHECK_FAILED == mUserInfo.getIdCheckStatus() || CtUserInfo.ID_CHECK_NONE == mUserInfo.getIdCheckStatus()) {
            mStep3.setBackgroundColor(ResourceUtil.getColor(R.color.ganshi_ded8d7));
        } else {
            mStep3.setBackgroundColor(ResourceUtil.getThemeColor());
        }
    }

    @OnClick(R.id.tv_code_select)
    public void selectCountryCode() {
        TrackUtil.trackScreenName("/user/verification/mobile/set/country");
        Intent intent = new Intent(getActivity(), CountryPageSelectActivity.class);
        startActivityForResult(intent, REQUEST_CODE_COUNTRY_COED);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case REQUEST_CODE_COUNTRY_COED:
                if (resultCode == Activity.RESULT_OK) {
                    countryCode = data.getStringExtra(CountryPageSelectActivity.KEY_CODE);
                    mCountryCode.setText(countryCode);
                }
                break;

            case REQUEST_CODE_VERIFIED_SUC:
                if (resultCode == Activity.RESULT_OK) {
                    CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();
                    if (CtUserInfo.ID_CHECK_FAILED == userInfo.getIdCheckStatus() || CtUserInfo.ID_CHECK_NONE == userInfo.getIdCheckStatus()) {
                        FragmentJumper.addFragment(getHostActivity().getCustomSelfFragmentManager(), R.id.container, VerifyIDFragment.newInstance(mServiceInfo, mUserInfo), VerifyIDFragment.class.getName(), false);
                    } else {
                        mServiceInfo.setOnlineState(ServiceInfo.ONLINE_STATE);
                        ServiceBusiness.commitServiceInfo(mApiProxy, mServiceInfo);
                        JumpSuccessUtil.navigate2CreateTripSucPage(this, REQUEST_CODE_ID_SUCCESS);

                    }
                }
                break;

        }
    }

    @Override
    public void initData() {
        initProgress();
    }

    @Override
    public void initListener() {
        mPhotoNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s == null || s.length() == 0) {
                    return;
                }
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < s.length(); ++i) {
                    if (i != 3 && i != 8 && s.charAt(i) == ' ') {
                        continue;
                    } else {
                        sb.append(s.charAt(i));
                        if ((sb.length() == 4 || sb.length() == 9) && sb.charAt(sb.length() - 1) != ' ') {
                            sb.insert(sb.length() - 1, ' ');
                        }
                    }
                }
                if (!sb.toString().equals(s.toString())) {
                    int index = start + 1;
                    if (sb.charAt(start) == ' ') {
                        if (before == 0) {
                            index++;
                        } else {
                            index--;
                        }
                    } else {
                        if (before == 1) {
                            index--;
                        }
                    }
                    mPhotoNumber.setText(sb.toString());
                    mPhotoNumber.setSelection(index);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @OnClick(R.id.tv_send)
    public void sendSms() {
        if (TextUtils.isEmpty(mPhotoNumber.getText())) {
            Utils.shakeView(mPhotoNumber);
        } else {

            new CountDownTimerUtil(30000,1000){

                @Override
                public void onTick(long millisUntilFinished) {
                    if (getActivity()==null ){
                        cancel();
                    }
                    if (getActivity()!=null){
                        mSendBtn.setText(getString(R.string.operation_resend) + "(" + millisUntilFinished / 1000 + ")");
                        mSendBtn.setEnabled(false);
                    }
                }

                @Override
                public void onFinish() {
                    mSendBtn.setText(getString(R.string.operation_send));
                    mSendBtn.setEnabled(true);
                }
            }.start();
            String photoNum = mPhotoNumber.getText().toString().replaceAll(" ", "");
            UserBusiness.sendVerifySMS(mApiProxy, countryCode, photoNum);
        }
    }

    @OnClick(R.id.tv_verify)
    public void verifyMobile() {
        if (!TextUtils.isEmpty(mPhotoNumber.getText()) && !TextUtils.isEmpty(mVerifiedCode.getText())) {
            String photoNumber = mPhotoNumber.getText().toString().replaceAll(" ", "");
            String verifiedCode = mVerifiedCode.getText().toString();
            showLoading();
            UserBusiness.verifySMS(mApiProxy, countryCode, photoNumber, verifiedCode);

        }
    }

    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        if (!isAdded()) {
            return false;
        }
        CtApiResponse response = (CtApiResponse) result.getData();
        hideLoading();
        if (response.isResponseNormal()) {
            if (response.getApiName().equals(ApiManager.VERIFY_PHONE)) {
                //验证手机成功，跳转页面
                StringBuilder builder = new StringBuilder();
                builder.append("+");
                builder.append(countryCode);
                builder.append(mPhotoNumber.getText());
                SubmitSuccessModel submitSuccessModel = new SubmitSuccessModel(SubmitSuccessModel.ContentType.VERIFIED_SUCCESS, getString(R.string.user_verify_state_2), builder.toString(), getString(R.string.operation_ok_1));
                SubmitSuccessActivity.launchSuccessPage(VerifyUserMoblieFragment.this, submitSuccessModel, REQUEST_CODE_VERIFIED_SUC);
            } else if (ApiManager.SERVICE_COMMIT.equals(response.getApiName())) {
                if (response.result instanceof ServiceInfo) {
                    ServiceInfo serviceInfo = (ServiceInfo) response.result;
                    mServiceInfo.setSid(serviceInfo.getSid());
                    LocalBroadcastManager.getInstance(AppCoreRuntime.context).sendBroadcast(
                            new Intent(TripServiceListFragment.TRIP_SERVICE_STATUS_CHANGED));
                    IndexActivity.gotoTab(getActivity(), IndexActivity.SERVICE_TAB_INDEX);
                    getActivity().finish();
                }
            }
        } else {
            if (!TextUtils.isEmpty(response.msg)) {
                MessageUtils.showToast(response.msg);
            }
        }
        return false;
    }

    @Override
    public void onTopbarRightPress() {
        if (mServiceInfo != null) {
            if (mServiceInfo.isUnSync() || mServiceInfo.isCheckFailed() || mServiceInfo.isDraft() || mServiceInfo.isChecking()) {
                if (ServiceFormProxy.getInstance().isFormComplete(mServiceInfo, FormType.TITLE)) {
                    showLoading();
                    mServiceInfo.setOnlineState(ServiceInfo.DRAFT_STATE);
                    ServiceBusiness.commitServiceInfo(mApiProxy, mServiceInfo);
                }
            }
        }

    }
}
